package com.example.demo.security.config;

import com.example.demo.security.AuthenticationEntryPointImpl;
import com.example.demo.security.filter.TokenFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * security 相关配置
 *
 * @author 叮当猫的百宝箱
 * @since 1.0
 */
@Slf4j
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration {

    @Bean
    public TokenFilter tokenFilter() {
        return new TokenFilter();
    }

    @Bean
    public AuthenticationEntryPoint authenticationEntryPoint() {
        return new AuthenticationEntryPointImpl();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        // 关闭csrf认证
        http.csrf().disable();

//        // session 管理， 全局不使用session
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.sessionManagement().sessionFixation().none();
        String[] permitList = new String[]{
                "/developer/**",
                "/adminUser/login",
                "/doc.html",
                "/**/*.css",
                "/**/*.js",
                "/v3/**"
        };
        // 认证的规则
        http.authorizeRequests()
                .antMatchers(permitList).permitAll()
                .anyRequest().authenticated();

        http.addFilterBefore(tokenFilter(), UsernamePasswordAuthenticationFilter.class);
        http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint());

        return http.build();
    }


    public String[] getPermitList() {
        return new String[]{
                "/adminUser/login",
                "/doc.html",
                "/**/*.css",
                "/**/*.js",
                "/v3/**"
        };
    }
}
